package com.android.examplelist;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
	
	private static final String DATABASE_NAME = "examplelist.db";
	private static final int DATABASE_VERSION = 1;
	
	
	private Dao<SimpleData, Integer> simpleDao = null;
	
	
	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
		try {
			TableUtils.createTable(connectionSource, SimpleData.class);
			
			Dao<SimpleData, Integer> dao = getSimpleDataDao();
			
			long millis = System.currentTimeMillis();
			SimpleData simple = new SimpleData(millis);
			dao.create(simple);
			
			simple = new SimpleData(millis + 1);
			dao.create(simple);
			
		}catch (SQLException e) {
			//Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
			throw new RuntimeException(e);
		}
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
		try {

			TableUtils.dropTable(connectionSource, SimpleData.class, true);
			// after we drop the old databases, we create the new ones
			onCreate(db, connectionSource);
		} catch (SQLException e) {

			throw new RuntimeException(e);
		}
		
	}
	
	
	public Dao<SimpleData, Integer> getSimpleDataDao() throws SQLException {
		if (simpleDao == null) {
			simpleDao = getDao(SimpleData.class);
		}
		return simpleDao;
	}

	@Override
	public void close() {
		super.close();
		simpleDao = null;
	}
	
}
